package com.car.advertising.util;

import android.content.Context;
import android.os.Looper;
import android.text.TextUtils;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.cache.ExternalCacheDiskCacheFactory;
import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory;

import java.io.File;
import java.math.BigDecimal;

/**
 * Glide缓存工具类
 * Created by Trojx on 2016/10/10 0010.
 */

public class GlideCacheUtil {
    private static GlideCacheUtil inst;

    public static GlideCacheUtil getInstance() {
        if (inst == null) {
            inst = new GlideCacheUtil();
        }
        return inst;
    }

    /**
     * 网络加载图片到ImageView中
     */
    public void loadNetworkImg(Context context) {
//        1.网络加载图片到ImageView中
//        Glide.with(context).load(imageUrl).into(imageView);

//        2.当加载网络图片时，由于加载过程中图片未能及时显示，此时可能需要设置等待时的图片，通过placeHolder()方法
//        Glide.with(context).load(imageUrl).placeholder(R.mipmap.ic_launcher).into(imageView);

//        3.当加载图片失败时，通过error(Drawable drawable)方法设置加载失败后的图片显示：
//        Glide.with(context).load(imageUrl).error(R.mipmap.ic_launcher).into(imageView);

//        4.图片的缩放，centerCrop()和fitCenter()：
//        1)使用centerCrop是利用图片图填充ImageView设置的大小，如果ImageView的Height是match_parent则图片就会被拉伸填充
//        Glide.with(context).load(imageUrl).centerCrop().into(imageView);
//        2)使用fitCenter即缩放图像让图像都测量出来等于或小于 ImageView 的边界范围,该图像将会完全显示，但可能不会填满整个ImageView。
//        Glide.with(context).load(imageUrl).fitCenter().into(imageView);

//        5.显示gif动画,asGif()判断是否是gif动画
//        Glide.with(context).load(imageUrl).asGif().into(imageView);

//        6.显示本地视频
//        String filePath = "/storage/emulated/0/Pictures/example_video.mp4";
//        Glide.with( context ).load( Uri.fromFile( new File( filePath ) ) ).into(imageViewGifAsBitmap );

//        7.缓存策略
//        Glide.with( context ).load(imageUrl).skipMemoryCache(true).into(imageViewInternet );//跳过内存缓存
//        Glide.with( context ).load(imageUrl).diskCacheStrategy(DiskCacheStrategy.NONE).into( imageViewInternet );//跳过硬盘缓存
//        DiskCacheStrategy.NONE 什么都不缓存
//        DiskCacheStrategy.SOURCE 仅仅只缓存原来的全分辨率的图像
//        DiskCacheStrategy.RESULT 仅仅缓存最终的图像，即降低分辨率后的（或者是转换后的）
//        DiskCacheStrategy.ALL 缓存所有版本的图像（默认行为）

//        8.优先级，设置图片加载的顺序：
//        Glide.with(context).load(imageUrl).priority( Priority.HIGH).into( imageView);

//        9.获取Bitmap，设置CircleImageVIew可以使用这个ImageView库
//        Glide.with(mContext)
//                .load(url)
//                .placeholder(R.drawable.loading_spinner)
//                .into(new SimpleTarget<Bitmap>(width, height) {
//                    @Override
//                    public void onResourceReady(Bitmap bitmap, GlideAnimation anim) {
//                        // setImageBitmap(bitmap) on CircleImageView
//                    }
//                };

//        10. 加载圆形图片和圆角图片
////圆形图片
//        public class GlideCircleTransform extends BitmapTransformation {
//            public GlideCircleTransform(Context context) {
//                super(context);
//            }
//
//            @Override
//            protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
//                return circleCrop(pool, toTransform);
//            }
//
//            private static Bitmap circleCrop(BitmapPool pool, Bitmap source) {
//                if (source == null) return null;
//
//                int size = Math.min(source.getWidth(), source.getHeight());
//                int x = (source.getWidth() - size) / 2;
//                int y = (source.getHeight() - size) / 2;
//
//                // TODO this could be acquired from the pool too
//                Bitmap squared = Bitmap.createBitmap(source, x, y, size, size);
//
//                Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888);
//                if (result == null) {
//                    result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
//                }
//
//                Canvas canvas = new Canvas(result);
//                Paint paint = new Paint();
//                paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
//                paint.setAntiAlias(true);
//                float r = size / 2f;
//                canvas.drawCircle(r, r, r, paint);
//                return result;
//            }
//
//            @Override
//            public String getId() {
//                return getClass().getName();
//            }
//        }

////圆角图片
//        public class GlideRoundTransform extends BitmapTransformation {
//
//            private static float radius = 0f;
//
//            public GlideRoundTransform(Context context) {
//                this(context, 4);
//            }
//
//            public GlideRoundTransform(Context context, int dp) {
//                super(context);
//                this.radius = Resources.getSystem().getDisplayMetrics().density * dp;
//            }
//
//            @Override
//            protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
//                return roundCrop(pool, toTransform);
//            }
//
//            private static Bitmap roundCrop(BitmapPool pool, Bitmap source) {
//                if (source == null) return null;
//
//                Bitmap result = pool.get(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
//                if (result == null) {
//                    result = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
//                }
//
//                Canvas canvas = new Canvas(result);
//                Paint paint = new Paint();
//                paint.setShader(new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
//                paint.setAntiAlias(true);
//                RectF rectF = new RectF(0f, 0f, source.getWidth(), source.getHeight());
//                canvas.drawRoundRect(rectF, radius, radius, paint);
//                return result;
//            }
//
//            @Override
//            public String getId() {
//                return getClass().getName() + Math.round(radius);
//            }
//        }
    }

    /**
     * 清除图片磁盘缓存
     */
    public void clearImageDiskCache(final Context cxt) {
        try {
            if (Looper.myLooper() == Looper.getMainLooper()) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Glide.get(cxt).clearDiskCache();
                    }
                }).start();
            } else {
                Glide.get(cxt).clearDiskCache();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 清除图片内存缓存
     */
    public void clearImageMemoryCache(Context context) {
        try {
            if (Looper.myLooper() == Looper.getMainLooper()) { //只能在主线程执行
                Glide.get(context).clearMemory();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 清除图片所有缓存
     */
    public void clearImageAllCache(Context context) {
        clearImageDiskCache(context);
        clearImageMemoryCache(context);
        String ImageExternalCatchDir = context.getExternalCacheDir() + ExternalCacheDiskCacheFactory.DEFAULT_DISK_CACHE_DIR;
        deleteFolderFile(ImageExternalCatchDir, true);
    }

    /**
     * 获取Glide造成的缓存大小
     *
     * @return CacheSize
     */
    public String getCacheSize(Context context) {
        try {
            return getFormatSize(getFolderSize(new File(context.getCacheDir() + "/" + InternalCacheDiskCacheFactory.DEFAULT_DISK_CACHE_DIR)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取指定文件夹内所有文件大小的和
     *
     * @param file file
     * @return size
     * @throws Exception
     */
    private long getFolderSize(File file) throws Exception {
        long size = 0;
        try {
            File[] fileList = file.listFiles();
            for (File aFileList : fileList) {
                if (aFileList.isDirectory()) {
                    size = size + getFolderSize(aFileList);
                } else {
                    size = size + aFileList.length();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }

    /**
     * 删除指定目录下的文件，这里用于缓存的删除
     *
     * @param filePath       filePath
     * @param deleteThisPath deleteThisPath
     */
    public void deleteFolderFile(String filePath, boolean deleteThisPath) {
        if (!TextUtils.isEmpty(filePath)) {
            try {
                File file = new File(filePath);
                if (file.isDirectory()) {
                    File files[] = file.listFiles();
                    for (File file1 : files) {
                        deleteFolderFile(file1.getAbsolutePath(), true);
                    }
                }
                if (deleteThisPath) {
                    if (!file.isDirectory()) {
                        file.delete();
                    } else {
                        if (file.listFiles().length == 0) {
                            file.delete();
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 格式化单位
     *
     * @param size size
     * @return size
     */
    private static String getFormatSize(double size) {

        double kiloByte = size / 1024;
        if (kiloByte < 1) {
            return size + "Byte";
        }

        double megaByte = kiloByte / 1024;
        if (megaByte < 1) {
            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "KB";
        }

        double gigaByte = megaByte / 1024;
        if (gigaByte < 1) {
            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "MB";
        }

        double teraBytes = gigaByte / 1024;
        if (teraBytes < 1) {
            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "GB";
        }
        BigDecimal result4 = new BigDecimal(teraBytes);

        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "TB";
    }
}